package com.wxf.controller;

import com.github.pagehelper.PageInfo;
import com.wxf.pojo.User;
import com.wxf.service.UserService;
import com.wxf.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/verifyCode")
    @ResponseBody
    public ResultVO getVerifyCode(HttpServletRequest req){
        int verifyCode = userService.getVerifyCode();
        System.out.println("验证码为："+verifyCode);
        req.getSession().setAttribute("verifyCode",verifyCode);
        return new ResultVO(verifyCode,"ok",200);
    }
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    public ResultVO login(String userName,String password,String verify,HttpServletRequest req){
        System.out.println(userName);
        System.out.println(password);
        System.out.println(verify);
        if(verify.equals(req.getSession().getAttribute("verifyCode"))){
            System.out.println(req.getSession().getAttribute("verifyCode"));
            return new ResultVO("验证码错误",401);
        }
        User user = userService.verifyUser(userName,password);
        //System.out.println(user);
        if(user==null){
            return new ResultVO("用户名或密码错误，请检查",402);
        }
        if(user.getUserState()==1){
            return new ResultVO("用户已被禁用",403);
        }
        ResultVO vo = new ResultVO(user,"登录成功",200);
        HttpSession session = req.getSession();
        session.setAttribute("userName",user.getUserLoginName());
        session.setAttribute("user",vo);
        return vo;
    }

    @RequestMapping(value = "/menu",method = RequestMethod.GET)
    @ResponseBody
    public ResultVO getUserMenu(HttpServletRequest req){
        HttpSession session = req.getSession();
        ResultVO vo = (ResultVO)session.getAttribute("user");
        System.out.println(vo);
        return vo;
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public ResultVO getUserList(Integer pageNum,Integer size){
        if(pageNum==null ||pageNum==0){
            pageNum=1;
        }
        if(size==null||size==0){
            size=5;
        }
        PageInfo pageInfo = userService.getUserListByPage(pageNum,size);
        if(pageInfo==null){
            return new ResultVO("服务器忙，请稍后再试",401);
        }
        ResultVO vo = new ResultVO("查询成功",200);
        vo.setPageInfo(pageInfo);
        System.out.println(pageInfo);
        return vo;
    }
}
